// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: hyuan

#pragma once

#include <cstdio>
#include <memory>
#include <set>
#include <string>

#include <rapidjson/document.h>

#include "coin2/exchange/base/order/order.h"
#include "coin2/exchange/kucoin/api_util/rate_tracker.h"
#include "coin2/exchange/kucoin/symbology/product.h"

namespace coin2::exchange::kucoin::order_v1 {

class KucoinParser : public base::order::BaseParser {
 public:
  using RateLimitInfo = coin2::exchange::kucoin::api_util::RateLimitInfo;

 public:
  const ParseResult& ParseRawMessage(const RawMessage& msg) override;
  AccountBalance ParseBalance(const JsonValue& doc) override;

 private:
  void ParseRestAccountBalance();
  void ParseRestAccountCrossBalance();
  void ParseRestOpenOrderInfoList();
  void ParseRestHistoryOrderInfoList();
  void ParseRestFillOrderInfoList();
  void ParseRestBullet();
  void ParseSubmitResponse();
  void ParseCancelResponse();
  void ParseRestTransfers();

  void ParseWsOrderInfoList(const JsonDocument& document);
  void ParseWsTradeInfoList(const JsonDocument& document);
  void ParseWsBalanceInfoList(const JsonDocument& document);
  void ParseWsMessage();

  void ParseRestOrder(ProductOrderElement* order, const JsonValue& data);
  void ParseRestFillInfo(ProductFillElement* fill, const JsonValue& data);

  int32_t ParseErrorMessage(const std::shared_ptr<AsioHttpContext>& http_context);

 private:
  RateLimitInfo enable_time_{0};
  bool is_bullet_initialized_{false};
  bool is_account_balance_initialized_ = false;
  std::map<std::string, std::string> transfer_map_;
  bool is_transfer_deposit_initialized_ = false;

  RawBalanceMap raw_cross_balance_cache_map_;
};

}  // namespace coin2::exchange::kucoin::order_v1
